import {
  Controller,
  Post,
  Get,
  UseGuards,
  UseInterceptors,
  UploadedFile,
  Request,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
  ApiConsumes,
} from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { UploadService } from './upload.service';
import { FileUploadResponseDto, UploadConfigResponseDto } from './dto/user.dto';

@ApiTags('文件上传')
@Controller('user')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('upload')
  @UseGuards(JwtAuthGuard)
  @UseInterceptors(FileInterceptor('file'))
  @ApiBearerAuth()
  @ApiConsumes('multipart/form-data')
  @ApiOperation({ summary: '上传文件到腾讯云COS' })
  @ApiResponse({
    status: 200,
    description: '上传成功',
    type: FileUploadResponseDto,
  })
  @ApiResponse({ status: 400, description: '文件类型不支持或文件过大' })
  @ApiResponse({ status: 401, description: '未授权' })
  @HttpCode(HttpStatus.OK)
  async uploadFile(@Request() req, @UploadedFile() file: Express.Multer.File) {
    if (!file) {
      return {
        code: 400,
        message: '请选择要上传的文件',
        data: null,
        timestamp: Date.now(),
      };
    }

    const result = await this.uploadService.uploadFile(file);

    return {
      code: 200,
      message: '文件上传成功',
      data: result,
      timestamp: Date.now(),
    };
  }

  @Get('upload/config')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取上传配置信息' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: UploadConfigResponseDto,
  })
  @ApiResponse({ status: 401, description: '未授权' })
  async getUploadConfig(@Request() req) {
    const result = this.uploadService.getUploadConfig();

    return {
      code: 200,
      message: '获取上传配置成功',
      data: result,
      timestamp: Date.now(),
    };
  }
}
